package com.itheima.stock.secuity.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.stock.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author: siwukun
 * @date: 2022/06/14
 * @description:
 */

public class AuthenticationFilter extends OncePerRequestFilter {


    /**
     * 权限认证filter
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //1.从http请求头中获取token
        String token = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        if (token==null){
            //用户登录放行，去登录拦截
            filterChain.doFilter(request,response);
            return;
        }
        Claims claims = JwtTokenUtil.checkJWT(token);
        if (claims==null){
            request.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            HashMap<String, String> info = new HashMap<>();
            info.put("status","0");
            info.put("ex","无效的token凭证");
            //响应错信息给前端
            response.getWriter().write(new ObjectMapper().writeValueAsString(info));
        }
        String username = JwtTokenUtil.getUsername(token);
        String userRole = JwtTokenUtil.getUserRole(token);
        //组装token
        //去除userRole中的[]
        String userR = StringUtils.strip(userRole, "[]");
        List<GrantedAuthority> listRole = AuthorityUtils.commaSeparatedStringToAuthorityList(userR);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, listRole);
        //token存到存到上下文
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //释放资源
        filterChain.doFilter(request,response);
    }
}
